package com.leo.service;

import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.leo.domain.Student;

public class CreateSimpleExcelToDisk {
	/**
	 * 生成一些学生的数据，真实开发中从数据库中获取
	 * @return
	 * @throws Exception
	 */
	public List<Student> getStudents() throws Exception{
		List<Student> students = new ArrayList<Student>();
		
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Student student1 = new Student(1, "张三", 18, format.parse("1991-01-12"));
		Student student2 = new Student(2, "李四", 17, format.parse("1992-01-12"));
		Student student3 = new Student(3, "王麻子", 28, format.parse("1982-01-12"));
		students.add(student1);
		students.add(student2);
		students.add(student3);
		
		return students;
	}
	
	
	public void createExcle() throws Exception{
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet 
		HSSFSheet hssfSheet = hssfWorkbook.createSheet("学生表一");
		// 第三步，在sheet中添加表头第0行
		HSSFRow hssfRow = hssfSheet.createRow(0);
		 // 第四步，创建单元格，并设置值表头 设置表头居中  
		HSSFCellStyle style = hssfWorkbook.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置一种居中的格式
		
		HSSFCell cell = hssfRow.createCell(0);
		cell.setCellValue("学号");
		cell.setCellStyle(style);
		cell = hssfRow.createCell(1);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = hssfRow.createCell(2);
		cell.setCellValue("年龄");
		cell.setCellStyle(style);
		cell = hssfRow.createCell(3);
		cell.setCellValue("生日");
		cell.setCellStyle(style);
		
		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		List<Student> list = this.getStudents();
		
		for (int i = 0; i < list.size(); i++) {
			hssfRow = hssfSheet.createRow(i+1);
			Student student = list.get(i);
			hssfRow.createCell(0).setCellValue(student.getId());
			hssfRow.createCell(1).setCellValue(student.getName());
			hssfRow.createCell(2).setCellValue(student.getAge());
			hssfRow.createCell(3).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(student.getBirth()));
		}
		
		// 第六步，将文件输出到指定位置
		FileOutputStream stream = new FileOutputStream("./test.xls");//本项目classpth的下面，即项目目录下面
		hssfWorkbook.write(stream);
		stream.close();
	}
}
